package cn.lblbc.ziptool

import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.FileProvider
import androidx.documentfile.provider.DocumentFile
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedInputStream
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream

class ArchiveContentActivity : AppCompatActivity() {
    
    private lateinit var toolbar: Toolbar
    private lateinit var recyclerView: RecyclerView
    private lateinit var extractButton: Button
    private lateinit var loadingProgressBar: ProgressBar
    private lateinit var adapter: ArchiveFileAdapter
    private var archiveUri: Uri? = null
    private var archiveName: String = ""
    private var currentPathPrefix: String = ""
    private val pathStack = mutableListOf<String>()
    
    // 添加缓存来存储已加载的目录内容
    private val contentCache = mutableMapOf<String, List<ArchiveFileItem>>()
    
    private val selectOutputDirContract = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
        uri?.let {
            try {
                // 获取持久化权限
                val takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION or 
                        Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                contentResolver.takePersistableUriPermission(it, takeFlags)
                
                archiveUri?.let { archiveUri ->
                    extractArchive(archiveUri, it)
                }
            } catch (e: Exception) {
                Log.e("ArchiveContentActivity", "Error processing selected directory", e)
                Toast.makeText(this, "处理目录时出错: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_archive_content)
        
        // 获取传递过来的压缩包URI和名称
        val archiveUriString = intent.getStringExtra("archive_uri")
        archiveName = intent.getStringExtra("archive_name") ?: "压缩包"
        
        if (archiveUriString != null) {
            archiveUri = Uri.parse(archiveUriString)
        } else {
            Toast.makeText(this, "未找到压缩包信息", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        initViews()
        setupToolbar()
        setupBackPressHandler()
        
        // 显示初始加载指示器
        loadingProgressBar.visibility = View.VISIBLE
        recyclerView.visibility = View.GONE
        
        loadArchiveContent(archiveUri!!, "")
    }
    
    private fun setupBackPressHandler() {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                // 如果有上级目录可以返回，则返回上级目录
                if (pathStack.isNotEmpty()) {
                    currentPathPrefix = pathStack.removeAt(pathStack.size - 1)
                    archiveUri?.let { uri ->
                        // 返回上级目录时不显示加载指示器，因为数据应该已经加载过了
                        loadArchiveContentWithoutLoadingIndicator(uri, currentPathPrefix)
                    }
                } else {
                    // 否则禁用回调并执行默认的返回键处理
                    isEnabled = false
                    onBackPressedDispatcher.onBackPressed()
                }
            }
        }
        onBackPressedDispatcher.addCallback(this, callback)
    }
    
    private fun setupToolbar() {
        toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
        
        // 设置标题和返回按钮
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            setDisplayShowHomeEnabled(true)
            title = archiveName
        }
        
        // 设置返回按钮点击事件，直接退出Activity
        toolbar.setNavigationOnClickListener {
            finish() // 直接退出当前Activity
        }
    }
    
    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerView)
        extractButton = findViewById(R.id.extractButton)
        loadingProgressBar = findViewById(R.id.loadingProgressBar)
        
        recyclerView.layoutManager = LinearLayoutManager(this)
        
        adapter = ArchiveFileAdapter(
            onItemClick = { fileItem ->
                Log.d("ArchiveContentActivity", "Item clicked: name=${fileItem.name}, isDirectory=${fileItem.isDirectory}, path=${fileItem.path}, fullPath=${fileItem.fullPath}")
                if (fileItem.isDirectory) {
                    // 保存当前路径
                    pathStack.add(currentPathPrefix)
                    // 更新路径前缀，确保目录路径以 "/" 结尾
                    currentPathPrefix = if (fileItem.path.endsWith("/")) fileItem.path else "${fileItem.path}/"
                    Log.d("ArchiveContentActivity", "Navigating to directory: ${currentPathPrefix}")
                    // 重新加载内容时显示加载指示器
                    loadingProgressBar.visibility = View.VISIBLE
                    recyclerView.visibility = View.GONE
                    // 重新加载内容
                    archiveUri?.let { uri ->
                        loadArchiveContent(uri, currentPathPrefix)
                    }
                } else if (fileItem.isTextFile() || isImageFile(fileItem.name)) {
                    // 在新Activity中打开文本文件或图片文件
                    archiveUri?.let { uri ->
                        openFileInViewer(uri, fileItem.fullPath, fileItem.name)
                    }
                } else if (isApkFile(fileItem.name)) {
                    // 安装APK文件
                    Log.d("ArchiveContentActivity", "APK file clicked: ${fileItem.name}")
                    archiveUri?.let { uri ->
                        installApkFromArchive(uri, fileItem.fullPath, fileItem.name)
                    }
                } else {
                    // 对于非文本文件，显示提示信息
                    Toast.makeText(this, "这是一个${getFileExtensionFromName(fileItem.name)}文件，无法在应用内预览", Toast.LENGTH_SHORT).show()
                }
            },
            onItemLongClick = { fileItem ->
                showFileContextMenu(fileItem)
            }
        )
        
        recyclerView.adapter = adapter
        
        // 设置解压按钮点击事件
        extractButton.setOnClickListener {
            selectOutputDirectory()
        }
    }
    
    private fun isImageFile(fileName: String): Boolean {
        val imageExtensions = setOf("jpg", "jpeg", "png", "gif", "bmp", "webp")
        val extension = fileName.substringAfterLast(".", "").lowercase()
        return extension in imageExtensions
    }
    
    private fun getFileExtensionFromName(fileName: String): String {
        val dotIndex = fileName.lastIndexOf('.')
        return if (dotIndex > 0) {
            fileName.substring(dotIndex + 1).uppercase()
        } else {
            "未知"
        }
    }
    
    private fun openFileInViewer(archiveUri: Uri, filePath: String, fileName: String) {
        val intent = Intent(this, FileViewerActivity::class.java).apply {
            putExtra("archive_uri", archiveUri)
            putExtra("file_path", filePath)
            putExtra("file_name", fileName)
        }
        startActivity(intent)
    }
    
    private fun showFileContextMenu(fileItem: ArchiveFileItem) {
        // 创建上下文菜单
        val items = if (isApkFile(fileItem.name)) {
            arrayOf("安装", "查看", "打开")
        } else {
            arrayOf("查看", "打开")
        }
        
        android.app.AlertDialog.Builder(this)
            .setTitle("选择操作")
            .setItems(items) { _, which ->
                when (which) {
                    0 -> {
                        if (isApkFile(fileItem.name)) {
                            // 安装APK
                            Log.d("ArchiveContentActivity", "Installing APK via context menu: ${fileItem.name}")
                            archiveUri?.let { uri ->
                                installApkFromArchive(uri, fileItem.fullPath, fileItem.name)
                            }
                        } else if (fileItem.isTextFile() || isImageFile(fileItem.name)) {
                            archiveUri?.let { uri ->
                                openFileInViewer(uri, fileItem.fullPath, fileItem.name)
                            }
                        } else {
                            Toast.makeText(this, "该文件类型无法预览", Toast.LENGTH_SHORT).show()
                        }
                    }
                    1 -> {
                        if (isApkFile(fileItem.name) && (fileItem.isTextFile() || isImageFile(fileItem.name))) {
                            archiveUri?.let { uri ->
                                openFileInViewer(uri, fileItem.fullPath, fileItem.name)
                            }
                        } else if (!isApkFile(fileItem.name)) {
                            // 对于非APK文件，尝试作为压缩包打开
                            openFileAsArchive(fileItem)
                        } else {
                            Toast.makeText(this, "该文件类型无法预览", Toast.LENGTH_SHORT).show()
                        }
                    }
                    2 -> {
                        // 对于APK文件，第三项是"打开"
                        openFileAsArchive(fileItem)
                    }
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 将文件作为压缩包打开
     */
    private fun openFileAsArchive(fileItem: ArchiveFileItem) {
        Log.d("ArchiveContentActivity", "Opening file as archive: ${fileItem.name}")
        
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 创建临时文件用于存储要打开的压缩包
                val tempFile = File(cacheDir, fileItem.name)
                var fileFound = false
                
                // 从当前压缩包中提取选中的文件到临时文件
                archiveUri?.let { uri ->
                    contentResolver.openInputStream(uri)?.use { inputStream ->
                        val fileExtension = getFileExtension(uri)
                        
                        when {
                            fileExtension.equals("zip", ignoreCase = true) || 
                            fileExtension.equals("apk", ignoreCase = true) || 
                            fileExtension.equals("xapk", ignoreCase = true) -> {
                                // 从ZIP文件中提取特定文件
                                ZipInputStream(BufferedInputStream(inputStream)).use { zipInputStream ->
                                    var entry: ZipEntry? = zipInputStream.nextEntry
                                    while (entry != null) {
                                        if (!entry.isDirectory && entry.name == fileItem.fullPath) {
                                            // 找到目标文件，提取到临时文件
                                            tempFile.outputStream().use { output ->
                                                zipInputStream.copyTo(output)
                                            }
                                            fileFound = true
                                            break
                                        }
                                        entry = zipInputStream.nextEntry
                                    }
                                }
                            }
                            else -> {
                                Log.e("ArchiveContentActivity", "Unsupported archive format for nested opening: $fileExtension")
                                withContext(Dispatchers.Main) {
                                    Toast.makeText(this@ArchiveContentActivity, "不支持的压缩包格式", Toast.LENGTH_SHORT).show()
                                }
                                return@launch
                            }
                        }
                    }
                }
                
                // 在主线程中启动新的ArchiveContentActivity来打开提取的压缩包
                withContext(Dispatchers.Main) {
                    if (fileFound && tempFile.exists()) {
                        val newUri = FileProvider.getUriForFile(
                            this@ArchiveContentActivity,
                            "${packageName}.fileprovider",
                            tempFile
                        )
                        val newIntent = Intent(this@ArchiveContentActivity, ArchiveContentActivity::class.java).apply {
                            putExtra("archive_uri", newUri.toString())
                            putExtra("archive_name", fileItem.name)
                        }
                        // 添加读取权限
                        newIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        startActivity(newIntent)
                    } else {
                        Toast.makeText(this@ArchiveContentActivity, "文件提取失败: 未找到文件", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                Log.e("ArchiveContentActivity", "Error extracting file from archive", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ArchiveContentActivity, "文件提取失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun loadArchiveContent(uri: Uri, prefix: String = "") {
        Log.d("ArchiveContentActivity", "Loading archive content with prefix: '$prefix'")
        // 显示加载指示器
        loadingProgressBar.visibility = View.VISIBLE
        recyclerView.visibility = View.GONE
        
        lifecycleScope.launch(Dispatchers.IO) {
            // 检查缓存中是否已有数据
            val fileItems = contentCache[prefix] ?: try {
                val items = ArchiveUtils.getArchiveEntries(this@ArchiveContentActivity, uri, prefix)
                // 缓存数据
                contentCache[prefix] = items
                items
            } catch (e: Exception) {
                Log.e("ArchiveContentActivity", "Error getting archive entries", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ArchiveContentActivity, "读取压缩包内容失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
                emptyList()
            }
            Log.d("ArchiveContentActivity", "Loaded ${fileItems.size} items with prefix: '$prefix'")
            
            withContext(Dispatchers.Main) {
                adapter.updateData(fileItems)
                // 隐藏加载指示器并显示内容
                loadingProgressBar.visibility = View.GONE
                recyclerView.visibility = View.VISIBLE
                Log.d("ArchiveContentActivity", "Updated adapter with ${fileItems.size} items")
            }
        }
    }
    
    /**
     * 不显示加载指示器的加载方法，用于返回上级目录等场景
     */
    private fun loadArchiveContentWithoutLoadingIndicator(uri: Uri, prefix: String = "") {
        Log.d("ArchiveContentActivity", "Loading archive content without loading indicator, prefix: '$prefix'")
        
        // 检查缓存中是否已有数据
        val cachedItems = contentCache[prefix]
        if (cachedItems != null) {
            // 如果缓存中有数据，立即显示
            Log.d("ArchiveContentActivity", "Using cached data for prefix: '$prefix', items: ${cachedItems.size}")
            adapter.updateData(cachedItems)
            return
        }
        
        // 如果缓存中没有数据，再从文件中加载
        lifecycleScope.launch(Dispatchers.IO) {
            val fileItems = try {
                val items = ArchiveUtils.getArchiveEntries(this@ArchiveContentActivity, uri, prefix)
                // 缓存数据
                contentCache[prefix] = items
                items
            } catch (e: Exception) {
                Log.e("ArchiveContentActivity", "Error getting archive entries", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ArchiveContentActivity, "读取压缩包内容失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
                emptyList()
            }
            Log.d("ArchiveContentActivity", "Loaded ${fileItems.size} items with prefix: '$prefix'")
            
            withContext(Dispatchers.Main) {
                adapter.updateData(fileItems)
                Log.d("ArchiveContentActivity", "Updated adapter with ${fileItems.size} items")
            }
        }
    }
    
    private fun selectOutputDirectory() {
        selectOutputDirContract.launch(null)
    }
    
    private fun extractArchive(archiveUri: Uri, outputUri: Uri) {
        extractButton.text = "解压中..."
        extractButton.isEnabled = false

        lifecycleScope.launch(Dispatchers.Main) {
            val success = extractArchiveToDirectory(archiveUri, outputUri) { progress ->
                extractButton.text = "解压中... ${progress}%"
            }

            extractButton.text = "解压"
            extractButton.isEnabled = true

            if (success) {
                Toast.makeText(this@ArchiveContentActivity, "解压成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@ArchiveContentActivity, "解压失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private suspend fun extractArchiveToDirectory(
        archiveUri: Uri, 
        outputUri: Uri,
        onProgress: (Int) -> Unit = {}
    ): Boolean = withContext(Dispatchers.IO) {
        return@withContext try {
            val documentFile = DocumentFile.fromTreeUri(this@ArchiveContentActivity, outputUri)
                ?: return@withContext false
            
            val fileExtension = getFileExtension(archiveUri)
            val fileName = getFileName(archiveUri)
            
            // 获取文件总数以计算进度
            val totalEntries = getTotalEntries(archiveUri, fileExtension)
            var processedEntries = 0
            
            when {
                fileExtension.equals("zip", ignoreCase = true) || 
                fileExtension.equals("apk", ignoreCase = true) || 
                fileExtension.equals("xapk", ignoreCase = true) -> {
                    extractZipToDocumentFile(archiveUri, documentFile) { 
                        processedEntries++
                        val progress = if (totalEntries > 0) (processedEntries * 100 / totalEntries) else 0
                        onProgress(progress.coerceAtMost(100))
                    }
                }
                fileExtension.equals("rar", ignoreCase = true) -> {
                    // 使用临时目录解压RAR，然后复制到目标目录
                    val tempDir = File(cacheDir, "temp_extract")
                    if (tempDir.exists()) tempDir.deleteRecursively()
                    tempDir.mkdirs()
                    
                    val success = try {
                        ArchiveUtils.extractArchive(this@ArchiveContentActivity, archiveUri, tempDir)
                    } catch (e: Exception) {
                        Log.e("ArchiveContentActivity", "Error extracting RAR archive", e)
                        false
                    }
                    
                    if (success) {
                        copyFilesToDocumentFile(tempDir, documentFile)
                    }
                    tempDir.deleteRecursively()
                    success
                }
                fileExtension.equals("7z", ignoreCase = true) -> {
                    // 使用临时目录解压7z，然后复制到目标目录
                    val tempDir = File(cacheDir, "temp_extract")
                    if (tempDir.exists()) tempDir.deleteRecursively()
                    tempDir.mkdirs()
                    
                    val success = try {
                        ArchiveUtils.extractArchive(this@ArchiveContentActivity, archiveUri, tempDir)
                    } catch (e: Exception) {
                        Log.e("ArchiveContentActivity", "Error extracting 7z archive", e)
                        false
                    }
                    
                    if (success) {
                        copyFilesToDocumentFile(tempDir, documentFile)
                    }
                    tempDir.deleteRecursively()
                    success
                }
                fileExtension.equals("gz", ignoreCase = true) && fileName.endsWith(".tar.gz", ignoreCase = true) -> {
                    // 使用临时目录解压tar.gz，然后复制到目标目录
                    val tempDir = File(cacheDir, "temp_extract")
                    if (tempDir.exists()) tempDir.deleteRecursively()
                    tempDir.mkdirs()
                    
                    val success = try {
                        ArchiveUtils.extractArchive(this@ArchiveContentActivity, archiveUri, tempDir)
                    } catch (e: Exception) {
                        Log.e("ArchiveContentActivity", "Error extracting tar.gz archive", e)
                        false
                    }
                    
                    if (success) {
                        copyFilesToDocumentFile(tempDir, documentFile)
                    }
                    tempDir.deleteRecursively()
                    success
                }
                else -> {
                    Log.e("ArchiveContentActivity", "Unsupported archive format: $fileExtension")
                    false
                }
            }
        } catch (e: Exception) {
            Log.e("ArchiveContentActivity", "Error extracting archive", e)
            false
        }
    }
    
    private fun getTotalEntries(uri: Uri, fileExtension: String): Int {
        return try {
            when {
                fileExtension.equals("zip", ignoreCase = true) || 
                fileExtension.equals("apk", ignoreCase = true) || 
                fileExtension.equals("xapk", ignoreCase = true) -> {
                    var count = 0
                    contentResolver.openInputStream(uri)?.use { inputStream ->
                        ZipInputStream(BufferedInputStream(inputStream)).use { zipInputStream ->
                            var entry: ZipEntry?
                            while (zipInputStream.nextEntry.also { entry = it } != null) {
                                entry?.let {
                                    if (!it.isDirectory) {
                                        count++
                                    }
                                }
                            }
                        }
                    }
                    count
                }
                else -> 0
            }
        } catch (e: Exception) {
            Log.e("ArchiveContentActivity", "Error counting entries", e)
            0
        }
    }
    
    private fun extractZipToDocumentFile(
        zipUri: Uri, 
        outputDir: DocumentFile,
        onEntryProcessed: () -> Unit = {}
    ): Boolean {
        try {
            contentResolver.openInputStream(zipUri)?.use { inputStream ->
                ZipInputStream(BufferedInputStream(inputStream)).use { zipInputStream ->
                    val buffer = ByteArray(8192)
                    var entry: ZipEntry?
                    
                    while (zipInputStream.nextEntry.also { entry = it } != null) {
                        entry?.let {
                            if (it.isDirectory) {
                                createDirectoryInDocumentTree(outputDir, it.name)
                            } else {
                                val entryName = it.name
                                val lastSlashIndex = entryName.lastIndexOf('/')
                                
                                // 如果文件在子目录中，确保创建父目录
                                val parentDocFile = if (lastSlashIndex != -1) {
                                    val parentPath = entryName.substring(0, lastSlashIndex)
                                    createDirectoryInDocumentTree(outputDir, parentPath)
                                } else {
                                    outputDir
                                }
                                
                                // 获取文件名（不包含路径）
                                val fileName = entryName.substring(lastSlashIndex + 1)
                                
                                // 创建文件
                                val newFile = parentDocFile.createFile("application/octet-stream", fileName)
                                
                                newFile?.let { file ->
                                    contentResolver.openOutputStream(file.uri)?.use { outputStream ->
                                        var len: Int
                                        while (zipInputStream.read(buffer).also { len = it } > 0) {
                                            outputStream.write(buffer, 0, len)
                                        }
                                        outputStream.flush()
                                    }
                                }
                                
                                // 通知处理了一个条目
                                onEntryProcessed()
                            }
                        }
                    }
                }
            }
            return true
        } catch (e: Exception) {
            Log.e("ArchiveContentActivity", "Error extracting ZIP to DocumentFile", e)
            return false
        }
    }
    
    private fun createDirectoryInDocumentTree(parent: DocumentFile, path: String): DocumentFile {
        var currentParent = parent
        val segments = path.split("/").filter { it.isNotEmpty() }
        
        for (segment in segments) {
            var dirDocument = findChildDocument(currentParent, segment, true)
            
            if (dirDocument == null) {
                dirDocument = currentParent.createDirectory(segment)
            }
            
            if (dirDocument != null) {
                currentParent = dirDocument
            } else {
                Log.e("ArchiveContentActivity", "Failed to create directory: $segment")
                break
            }
        }
        
        return currentParent
    }
    
    private fun findChildDocument(parent: DocumentFile, displayName: String, isDirectory: Boolean): DocumentFile? {
        for (child in parent.listFiles()) {
            if (child.name == displayName && child.isDirectory == isDirectory) {
                return child
            }
        }
        return null
    }
    
    private fun copyFilesToDocumentFile(sourceDir: File, destDir: DocumentFile) {
        sourceDir.listFiles()?.forEach { file ->
            if (file.isDirectory) {
                val newDir = destDir.createDirectory(file.name) ?: return@forEach
                copyFilesToDocumentFile(file, newDir)
            } else {
                val newFile = destDir.createFile("application/octet-stream", file.name) ?: return@forEach
                contentResolver.openOutputStream(newFile.uri)?.use { outputStream ->
                    file.inputStream().use { inputStream ->
                        inputStream.copyTo(outputStream)
                    }
                }
            }
        }
    }
    
    private fun getFileExtension(uri: Uri): String {
        val fileName = getFileName(uri)
        val dotIndex = fileName.lastIndexOf('.')
        return if (dotIndex > 0) {
            fileName.substring(dotIndex + 1)
        } else {
            ""
        }
    }
    
    private fun getFileName(uri: Uri): String {
        var result: String? = null
        contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val nameIndex = cursor.getColumnIndex("_display_name")
                if (nameIndex >= 0) {
                    result = cursor.getString(nameIndex)
                }
            }
        }
        return result ?: "unknown"
    }
    
    private fun isApkFile(fileName: String): Boolean {
        val extension = fileName.substringAfterLast(".", "").lowercase()
        return extension == "apk"
    }
    
    private fun installApkFromArchive(archiveUri: Uri, filePath: String, fileName: String) {
        Log.d("ArchiveContentActivity", "Installing APK from archive: filePath=$filePath, fileName=$fileName")
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 创建临时文件用于存储APK
                val tempFile = File(cacheDir, fileName)
                Log.d("ArchiveContentActivity", "Created temp file: ${tempFile.absolutePath}")
                
                contentResolver.openInputStream(archiveUri)?.use { archiveInputStream ->
                    // 根据文件扩展名处理不同类型的压缩包
                    val fileExtension = getFileExtension(archiveUri)
                    Log.d("ArchiveContentActivity", "Archive file extension: $fileExtension")
                    
                    when {
                        fileExtension.equals("zip", ignoreCase = true) || 
                        fileExtension.equals("apk", ignoreCase = true) || 
                        fileExtension.equals("xapk", ignoreCase = true) -> {
                            Log.d("ArchiveContentActivity", "Processing ZIP/APK archive")
                            // 从ZIP文件中提取特定文件
                            ZipInputStream(BufferedInputStream(archiveInputStream)).use { zipInputStream ->
                                var entry: ZipEntry? = zipInputStream.nextEntry
                                var found = false
                                while (entry != null && !found) {
                                    Log.d("ArchiveContentActivity", "Processing entry: ${entry.name}")
                                    if (!entry.isDirectory && entry.name == filePath) {
                                        // 找到目标APK文件，提取到临时文件
                                        Log.d("ArchiveContentActivity", "Found target APK file, extracting...")
                                        tempFile.outputStream().use { output ->
                                            zipInputStream.copyTo(output)
                                        }
                                        found = true
                                        Log.d("ArchiveContentActivity", "APK extracted successfully")
                                    }
                                    if (!found) {
                                        entry = zipInputStream.nextEntry
                                    }
                                }
                                if (!found) {
                                    Log.e("ArchiveContentActivity", "APK file not found in archive: $filePath")
                                }
                            }
                        }
                        else -> {
                            Log.e("ArchiveContentActivity", "Unsupported archive format: $fileExtension")
                            withContext(Dispatchers.Main) {
                                Toast.makeText(this@ArchiveContentActivity, "不支持的压缩包格式", Toast.LENGTH_SHORT).show()
                            }
                            return@launch
                        }
                    }
                }
                
                // 在主线程中启动安装
                withContext(Dispatchers.Main) {
                    Log.d("ArchiveContentActivity", "Checking if temp file exists: ${tempFile.exists()}")
                    if (tempFile.exists()) {
                        Log.d("ArchiveContentActivity", "Launching APK installation")
                        installApk(tempFile)
                    } else {
                        Log.e("ArchiveContentActivity", "APK file extraction failed - temp file doesn't exist")
                        Toast.makeText(this@ArchiveContentActivity, "APK文件提取失败", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                Log.e("ArchiveContentActivity", "Error extracting APK from archive", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ArchiveContentActivity, "APK文件提取失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    
    private fun installApk(apkFile: File) {
        try {
            Log.d("ArchiveContentActivity", "Installing APK: ${apkFile.absolutePath}")
            
            // 检查是否具有安装包权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (!packageManager.canRequestPackageInstalls()) {
                    Log.d("ArchiveContentActivity", "No permission to install packages, redirecting to settings")
                    Toast.makeText(this, "请允许安装应用权限", Toast.LENGTH_LONG).show()
                    
                    val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                        .setData(Uri.parse("package:$packageName"))
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                    return
                }
            }
            
            val intent = Intent(Intent.ACTION_VIEW)
            val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // For Android 7.0 and above, use FileProvider
                Log.d("ArchiveContentActivity", "Using FileProvider for Android N+")
                FileProvider.getUriForFile(
                    this,
                    "${packageName}.fileprovider",
                    apkFile
                )
            } else {
                // For older versions, use Uri.fromFile
                Log.d("ArchiveContentActivity", "Using Uri.fromFile for older Android versions")
                Uri.fromFile(apkFile)
            }
            
            Log.d("ArchiveContentActivity", "APK URI: $uri")
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            
            // 为所有可能接收该intent的应用添加读权限
            val resInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
            for (resolveInfo in resInfoList) {
                val packageName = resolveInfo.activityInfo.packageName
                grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
            }
            
            Log.d("ArchiveContentActivity", "Starting activity to install APK")
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            Log.e("ArchiveContentActivity", "No activity found to handle APK installation", e)
            Toast.makeText(this, "未找到APK安装程序: ${e.message}", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e("ArchiveContentActivity", "Error installing APK", e)
            Toast.makeText(this, "无法启动安装程序: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                finish() // 直接退出当前Activity
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    override fun onSupportNavigateUp(): Boolean {
        finish() // 直接退出当前Activity
        return true
    }
}